//数据收集，跨域处理中间件
module.exports = options => {
    return (ctx, next) => {
        ctx.set({
            'Access-Control-Allow-Origin': '*',
            "Access-Control-Allow-Headers": 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With',
            "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
        });

        if (ctx.method === "OPTIONS") {
            ctx.body = 'allow access';
            return false;
        }

        let data = ctx.post("data");
        if (ctx.isPost && data) {

            if (!data) {
                return ctx.fail(-1, '没有data数据域');
            }
            try {
                ctx.state.pd = JSON.parse(data);

            } catch (e) {
                return ctx.fail(-1, 'data数据域必须为json(解析错误)');
            }

        }
        return next();

        /*  {
              //禁止不合法的访问
              let path = ctx.path;
              let patt = /^(?:\/apiv1\/)+.+/;
              let res1 = patt.test(path);


              let staticPatt = /^(?:\/uploads\/)+.+/;
              let res2 = staticPatt.test(path);

              if (res1 === false && res2 === false) {
                  ctx.body = '就是不让你用~';
                  return false;
              } else {
                  //跨域问题
                  ctx.set({
                      'Access-Control-Allow-Origin': '*',
                      "Access-Control-Allow-Headers": 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With',
                      "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
                  });
                  return next();
              }
          }*/
    }
};